using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Inventory
{
    private Dictionary<ItemConfigData, int> itemDict = new();

    public void LoadFromList(string json, ItemDatabase database)
    {
        //Debug.Log($"Loading inventory from JSON: {json}");
        itemDict.Clear();
        var itemList = JsonConvert.DeserializeObject<List<ItemMap>>(json);
        foreach (var item in itemList)
        {
            itemDict[database.GetItemById(item.itemId)] = item.quantity;
        }
    }

    public List<KeyValuePair<ItemConfigData, int>> GetByCategory(string category)
    {
        return itemDict
            .Where(item => item.Key.type == category && item.Value > 0)
            .OrderByDescending(item => item.Key.rarity)
            .ToList();
    }

    public List<KeyValuePair<ItemConfigData, int>> GetAll()
    {
        return itemDict
            .Where(item => item.Value > 0)
            .OrderByDescending(item => item.Key.rarity)
            .ToList();
    }
}

[System.Serializable]
public class ItemMap
{
    public string itemId;
    public int quantity;
}
